package com.gome.ss.core.schedule;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.quartz.Trigger;
import org.quartz.TriggerBuilder;


public class TriggerStartIncremental extends TriggerConfig implements TriggerStart{
	private String name = "start-incremental";
	private String group = "cycle";
	private Date at;
	private int interval = 0;
	private String unit = "Minute"; // Minute Hour Day
	private boolean first = true;
	
	public TriggerStartIncremental(int interval, String unit) {
		this.interval = interval;
		this.unit = unit;
		this.setTriggerName(name);
		this.setTrggerGroup(group);
		this.triggerType = TriggerConfig.CYCLE_TYPE;
	}
	
	public void setName(String name) {
		this.name = name;
		this.setTriggerName(name);
	}
	
	public void setGroup(String group) {
		this.group = group;
		this.setTrggerGroup(group);
	}
	
	public Trigger getTrigger() {
		if (first) {
			this.at = new Date();
			this.first = false;
		} else {
			Date now = new Date();
			Calendar cal = Calendar.getInstance();
			cal.setTime(now);
			if (this.unit.equals("Minute")) {
				cal.add(Calendar.MINUTE, interval);
			} else if (this.unit.equals("Hour")) {
				cal.add(Calendar.HOUR, interval);
			} else if (this.unit.equals("Day")) {
				cal.add(Calendar.DATE, interval);
			} else {
				cal.add(Calendar.DATE, 7);
			}
			this.at = cal.getTime();
		}
		Trigger trigger = TriggerBuilder.newTrigger().withIdentity(this.getTriggerName(), this.getTrggerGroup()).startAt(at).build();
		return trigger;
	}

	@Override
	public String time() {
		return at.toString();
	}
}
